package com.example.websocket.component;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import java.util.List;
import java.util.Map;

/**
 * @author zty
 * @apiNote
 * @user nav1c
 * @date 2023/11/26 17:39
 * @project study-cloud
 */
@Slf4j
@Component
public class MainHandshakeInterceptor implements HandshakeInterceptor {

    /**
     * 握手之前的操作
     * @param request ServerHttpRequest
     * @param response ServerHttpResponse
     * @param wsHandler WebSocketHandler
     * @param attributes attributes
     * @return 是否握手成功
     */
    @Override
    public boolean beforeHandshake(@NonNull ServerHttpRequest request, @NonNull ServerHttpResponse response,
                                   @NonNull WebSocketHandler wsHandler, @NonNull Map<String, Object> attributes) {
        //这里可以放置业务鉴权业务处理
        log.info("准备握手-------");
        final List<String> keys = request.getHeaders().get("token");//不能用Authorization, 会导致鉴权报错
        if (CollectionUtils.isEmpty(keys)){
            return false;
        }
        attributes.clear();
        return true;
    }

    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) {

    }
}
